//
//  LoginMainView.swift
//  GuMro
//
//  Created by mac on 2019/12/3.
//  Copyright © 2019 cn.gomro.app. All rights reserved.
//

import UIKit
import LocalAuthentication

/**
 * LoginMainView
 */
class LoginMainView: BaseView {
    
    private var viewModel:LoginViewModel?
    
    private let cell_height = 32
    private let cell_margin_left = 53.4
    private let cell_bottom = 44

    private let txt_color = UIColor.init().colorFromHexString(hex: "#333333")
    private let txt_ccolor = UIColor.init(hexString:"#999999")
    private let txt_font = UIFont.systemFont(ofSize: 16)

    private let txt_botom_color = UIColor.init().colorFromHexString(hex:"#CCCCCC")
    private let txt_bottom_font = UIFont.systemFont(ofSize: 13)

    
    //MARK: - override
    override init(ViewModel vm: ViewModelProtocol) {
        self.viewModel = vm as? LoginViewModel
        super.init(ViewModel: vm)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func updateConstraints() {

        self.loginImg.snp.makeConstraints {[weak self] make in
            guard let self = self else { return }
        
            make.width.equalTo(96.5)
            make.height.equalTo(49.5)
            make.top.equalTo(82.5 + K_APP_SAFETY_NAV_HEIGHT)
            make.centerX.equalTo(self.snp.centerX)
        }
        
        self.txtUser.snp.makeConstraints {[weak self] make in
            guard let self = self else { return }
            
            make.left.equalTo(cell_margin_left)
            make.right.equalTo(-cell_margin_left)
            make.height.equalTo(cell_height)
            make.top.equalTo(self.loginImg.snp.bottom).offset(cell_bottom)
        }
        
        self.txtUser.bottomLine.snp.makeConstraints { make in
            make.left.right.bottom.equalTo(0)
            make.height.equalTo(0.5)
        }
        
        self.txtPwd.snp.makeConstraints {[weak self] make in
            guard let self = self else { return }
            
            make.left.equalTo(cell_margin_left)
            make.right.equalTo(-cell_margin_left)
            make.height.equalTo(cell_height)
            make.top.equalTo(self.txtUser.snp.bottom).offset(cell_bottom)
        }
        
        self.txtPwd.bottomLine.snp.makeConstraints { make in
            make.left.right.bottom.equalTo(0)
            make.height.equalTo(0.5)
        }
        
        self.btnLogin.snp.makeConstraints {[weak self] make in
            guard let self = self else { return }
            
            make.left.equalTo(cell_margin_left)
            make.right.equalTo(-cell_margin_left)
            make.height.equalTo(39)
            make.top.equalTo(self.txtPwd.snp.bottom).offset(cell_bottom)
        }
    
        self.btnKeep.snp.makeConstraints {[weak self] make in
            guard let self = self else { return }
            
            make.left.equalTo(cell_margin_left)
            make.width.equalTo(80)
            make.height.equalTo(44)
            make.top.equalTo(self.btnLogin.snp.bottom).offset(27)
        }
        
        self.btnForget.snp.makeConstraints {[weak self] make in
            guard let self = self else { return }
            
            make.right.equalTo(-cell_margin_left)
            make.width.equalTo(80)
            make.height.equalTo(44)
            make.top.equalTo(self.btnLogin.snp.bottom).offset(27)
        }
        
        self.btnNoAccount.snp.makeConstraints {[weak self] make in
            guard let self = self else { return }
            
             make.width.equalTo(183)
             make.height.equalTo(12.4)
             make.centerX.equalTo(self.snp.centerX)
             make.bottom.equalTo(self.snp.bottom).offset(UIDevice.current.isSimulator ? -29 : -49)
        }
        
        self.btnTouchIDLogin.snp.makeConstraints { [weak self] make in
            guard let self = self else { return }
            make.centerX.equalTo(self.snp.centerX)
            make.bottom.equalTo(self.btnNoAccount.top).offset(UIDevice.current.isSimulator ? -76 : -106)
        }
        
        super.updateConstraints()
    }
    
    override func setupViews() {
    
        self.addSubview(self.loginImg)
        self.addSubview(self.txtUser)
        self.addSubview(self.txtPwd)
        self.addSubview(self.btnLogin)
        self.addSubview(self.btnKeep)
        self.addSubview(self.btnForget)
        self.addSubview(self.btnNoAccount)
        self.addSubview(self.btnTouchIDLogin)
        self.btnTouchIDLogin.isHidden = !UserModel.touchIDLogin
        
        setNeedsUpdateConstraints()
    }
    
    
    //MARK: - 登录
    @IBAction private func btnLoginAction(sender:UIButton?){
        
        self.viewModel?.loginInCommand.execute([
            self.txtUser.text ?? "",
            self.txtPwd.text ?? ""
        ])
    }
    
    
    //MARK: - 记住密码
    @IBAction private func btnKeepAction(sender:UIButton){
        sender.isSelected = !sender.isSelected
        self.viewModel?.isSelected = sender.isSelected
        
        //移除密码
        guard let txt = self.txtUser.text,sender.isSelected == false,txt != "" else {
            return
        }
     
        DispatchQueue.global().async {
            let result = FMDBUtils.shareInstance.removePwdFor(User: txt)
            print("\(txt)密码已移除：\(result ? "成功":"失败")")
        }
    }
    
    
    //MARK: - 忘记密码
    @IBAction private func btnForgetAction(sender:UIButton){
        self.viewModel?.forgetPwdSubject.sendNext(nil)
    }
    
    
    //MARK: - 没有账号
    @IBAction private func btnNOAction(sender:UIButton){
        print("没有账号")
        //SVProgressHUD.showInfo(withStatus:"没有账号")
    }
    
    
    //MARK: - lazy load
    private lazy var loginImg:UIImageView = {
        let _login = YYImage.init(named: "logo")
        let _img = UIImageView.init(image: _login)
        return _img
    }()
    
    private lazy var txtUser:ANCustomTextField = {
        let _txt = ANCustomTextField.init()
        
        //_txt.keyboardType = .phonePad
        _txt.returnKeyType = .next
        
        //左边图标
        _txt.leftNormalImage = YYImage.init(named: "login_accout")
        _txt.leftPadding = 32.6
        _txt.leftViewMode = .always
        
        _txt.delegate = self
        _txt.hasBorder = false
        _txt.hasBottomBorder = true
        _txt.borderStyle = .none
        _txt.bottomLine.backgroundColor = K_APP_SPLIT_LINE_COLOR
        
        //清除
        _txt.clearButtonMode = .whileEditing
        
        _txt.textColor = txt_color
        _txt.font = txt_font
        
        //提示文本颜色
        _txt.placeholder = "请输入账号(区分大小写)"
        _txt.attributedPlaceholder = Utils.shareInstance().setPlaceholderAttributeString(ForFullText: _txt.placeholder!,
                                                                    ChangeText: _txt.placeholder!,
                                                                withChangeFont: _txt.font!,
                                                               withChangeColor: txt_ccolor,
                                                                 isLineThrough: false)
        
        return _txt
    }()
    
    private lazy var txtPwd:ANCustomTextField = {
        let _txt = ANCustomTextField.init()
        
        //密码框
        _txt.isSecureTextEntry = true
        
        _txt.keyboardType = .default
        _txt.returnKeyType = .send
        
        //左边图标
        _txt.leftNormalImage = YYImage.init(named: "login_pwd")
        _txt.leftPadding = 32.6
        _txt.leftViewMode = .always
        
        _txt.delegate = self
        _txt.hasBorder = false
        _txt.hasBottomBorder = true
        _txt.borderStyle = .none
        _txt.bottomLine.backgroundColor = K_APP_SPLIT_LINE_COLOR
        
        //清除
        _txt.clearButtonMode = .whileEditing
        
        _txt.textColor = txt_color
        _txt.font = txt_font
        
        //提示文本颜色
        _txt.placeholder = "请输入密码"
        _txt.attributedPlaceholder = Utils.shareInstance().setPlaceholderAttributeString(ForFullText: _txt.placeholder!,
                                                                    ChangeText: _txt.placeholder!,
                                                                withChangeFont: _txt.font!,
                                                               withChangeColor: txt_ccolor,
                                                                 isLineThrough: false)
        
        return _txt
    }()
    
    //登录
    private lazy var btnLogin:UIButton = {
        let _btn = BaseView.createBtn(rect: CGRect.zero,
                             strTitle: "登录",
                             titleColor: UIColor.white,
                             txtFont: txt_font,
                             image: nil,
                             backgroundColor: K_APP_TINT_COLOR,
                             borderColor: nil,
                             cornerRadius: 5,
                             isRadius: true,
                             backgroundImage: nil,
                             borderWidth: 0)
        
        _btn.showsTouchWhenHighlighted = true
        _btn.addTarget(self, action: #selector(btnLoginAction(sender:)), for: .touchUpInside)
        
        return _btn
    }()
    
    //记住密码
    lazy var btnKeep:UIButton = {
        let _btn = BaseView.createBtn(rect: CGRect.zero,
                             strTitle: "记住密码",
                             titleColor: txt_botom_color,
                             txtFont: txt_bottom_font,
                             image: YYImage.init(named: "login_cbo"),
                             backgroundColor: nil,
                             borderColor: nil,
                             cornerRadius: 0,
                             isRadius: false,
                             backgroundImage: nil,
                             borderWidth: 0)
        
        
        _btn.titleEdgeInsets = .init(top: 0, left: 6, bottom: 0, right: 0)
        _btn.setImage(YYImage.init(named: "login_select"), for: .selected)
        _btn.addTarget(self, action: #selector(btnKeepAction(sender:)), for: .touchUpInside)
        
        return _btn
    }()
    
    //忘记密码
    private lazy var btnForget:UIButton = {
        let _btn = BaseView.createBtn(rect: CGRect.zero,
                             strTitle: "忘记密码",
                             titleColor: txt_botom_color,
                             txtFont: txt_bottom_font,
                             image: YYImage.init(named: "login_fpw"),
                             backgroundColor: nil,
                             borderColor: nil,
                             cornerRadius: 0,
                             isRadius: false,
                             backgroundImage: nil,
                             borderWidth: 0)
        
        _btn.titleEdgeInsets = .init(top: 0, left: 6, bottom: 0, right: 0)
        _btn.addTarget(self, action: #selector(btnForgetAction(sender:)), for: .touchUpInside)
        
        return _btn
    }()
    
    //没有账号
    private lazy var btnNoAccount:UIButton = {
        let _btn = BaseView.createBtn(rect: CGRect.zero,
                             strTitle: "没有固买账号？请联系我们 >",
                             titleColor: txt_color,
                             txtFont: txt_bottom_font,
                             image: nil,
                             backgroundColor: nil,
                             borderColor: nil,
                             cornerRadius: 0,
                             isRadius: false,
                             backgroundImage: nil,
                             borderWidth: 0)
        _btn.contentMode = .center
        
        let _attStr = Utils.shareInstance().setAttributeStringText(strFullText: "没有固买账号？请联系我们 >",
                                             andFullTextFont: txt_bottom_font,
                                             andFullTextColor: txt_color,
                                             withChangeText: "请联系我们 >",
                                             withChangeFont: txt_bottom_font,
                                             withChangeColor: K_APP_TINT_COLOR)
        _btn.setAttributedTitle(_attStr, for: .normal)
        
        _btn.addTarget(self, action: #selector(btnNOAction(sender:)), for: .touchUpInside)
        
        return _btn
    }()
    
    private lazy var btnTouchIDLogin:UIButton = {
        let _btn = BaseView.createButton(rect: CGRect.init(x: 0, y: 0, width: 56, height: 56),
                                         bottonTitle: "指纹登录",
                                         titleColor: K_APP_TINT_COLOR,
                                         titleFont: txt_bottom_font,
                                         contentImg: YYImage.init(named: "login_touchID.png")!,
                                         bgImage: nil)

        _btn.rac_signal(for: .touchUpInside)?.subscribeNext({[weak self] (input:Any?) in
            guard let self = self else { return }
            let _context:LAContext = LAContext.init()
            
            _context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: "通过Home键验证指纹登录", reply: { (success:Bool, _error:Error?) in
                
                if success && _error == nil {
                    let (_un,_pwd) = FMDBUtils.shareInstance.getTouchIDInfo()
                    if _un != nil && _un != "" && _pwd != nil && _pwd != "" {
                        //调用登录方法
                        DispatchQueue.main.async {
                            self.viewModel?.loginInCommand.execute([_un!,_pwd!])
                        }
                    }
                    else{
                        SVProgressHUD.showInfo(withStatus: "暂未开启指纹登录")
                    }
                }
                else{
                    print(_error?.localizedDescription ?? "TouchID 验证失败")
                    SVProgressHUD.showInfo(withStatus: "TouchID 验证失败")
                }
                
                //释放
                _context.invalidate()
            })
        })
        
        return _btn
    }()
}


//MARK: - UITextFieldDelegate
extension LoginMainView: UITextFieldDelegate {
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {

        if textField == self.txtPwd {
            self.btnLoginAction(sender: nil)
        }
        else if textField == self.txtUser {
            self.txtPwd.becomeFirstResponder()
        }

        return true
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        guard let txt:String = textField.text,textField == self.txtUser,txt.count > 0 else {
            return
        }
        
        DispatchQueue.global().async {
            //查找对应密码
            let pwd:String? = FMDBUtils.shareInstance.getPwdFor(User: txt)
            print("uname:\(txt),pwd:\(pwd ?? "")")
            
            DispatchQueue.main.async {
                self.txtPwd.text = pwd
                
                if pwd != nil && pwd != "" {
                    self.btnKeep.isSelected = true
                }
            }
        }
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        // [S] 禁止用户切换键盘为Emoji表情
        if textField.isFirstResponder {
            if textField.textInputMode?.primaryLanguage == "emoji" || textField.textInputMode?.primaryLanguage == nil {
                return false
            }
        }
        // [E] 禁止用户切换键盘为Emoji表情

//        let length = textField.text?.count ?? 0
//        let strLength = string.lengthOfBytes(using: String.Encoding.utf8)

//        if (length == 3 || length == 8) && strLength != 0 && textField == self.txtUser {
//            textField.text = textField.text! + " "
//        }

//        //电话长度限制
//        if strLength != 0 && textField == self.txtUser && length >= 13 {
//            return false
//        }
        
        //判断输入的字是否是回车，即按下return
        if string == "\n" {
            self.btnLoginAction(sender: nil)

            //在这里做你响应return键的代码
            return false
        }

        return true
    }
}
